//
//  Liu70GIFAnalyzer.m
//
//  Created by Liu70 on 2018/3/12.
//  Copyright © 2018年 Liu. All rights reserved.
//

#import "Liu70GIFAnalyzer.h"
#import <UIKit/UIKit.h>

@interface Liu70GIFAnalyzer ()

@property (nonatomic, strong) NSMutableArray *framesArrayX;
@property (nonatomic, assign) CGFloat animationTime;

@end

@implementation Liu70GIFAnalyzer

- (instancetype)initWithGIFData:(NSData*)data {
    if (self = [super init]) {
        self.framesArrayX = [self praseGIFDataToImageArray:data];
    }
    return self;
}

- (instancetype)initWithGIFName:(NSString*)name type:(NSString*)type {
    NSString *path = [[NSBundle mainBundle]pathForResource:name ofType:type];
    return [self initWithGIFData:[NSData dataWithContentsOfFile:path]];
}

- (NSInteger)totalFrames {
    return self.framesArrayX.count;
}

- (NSInteger)frameRate {
    NSInteger i = self.framesArrayX.count / self.animationTime + 0.1;
    return i;
}

- (NSMutableArray *)framesArray {
    return self.framesArrayX;
}

- (NSMutableArray *)praseGIFDataToImageArray:(NSData *)data {
    NSMutableArray *frames = [[NSMutableArray alloc] init];
    CGImageSourceRef src = CGImageSourceCreateWithData((CFDataRef)data, NULL);
    CGFloat animationTime = 0.f;
    if (src) {
        size_t l = CGImageSourceGetCount(src);
        frames = [NSMutableArray arrayWithCapacity:l];
        for (size_t i = 0; i < l; i++) {
            CGImageRef img = CGImageSourceCreateImageAtIndex(src, i, NULL);
            NSDictionary *properties = (NSDictionary *)CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(src, i, NULL));
            NSDictionary *frameProperties = [properties objectForKey:(NSString *)kCGImagePropertyGIFDictionary];
            NSNumber *delayTime = [frameProperties objectForKey:(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
            animationTime += [delayTime floatValue];
            if (img) {
                [frames addObject:[UIImage imageWithCGImage:img]];
                CGImageRelease(img);
            }
        }
        CFRelease(src);
    }
    self.animationTime = animationTime;
    return frames;
}

@end
